package demo2;

import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.layout.borders.SolidBorder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

// 套餐产品项
class ComboItem {
    private int serialNumber;
    private String productName;
    private int quantity;

    public ComboItem(int serialNumber, String productName, int quantity) {
        this.serialNumber = serialNumber;
        this.productName = productName;
        this.quantity = quantity;
    }

    public int getSerialNumber() {
        return serialNumber;
    }

    public String getProductName() {
        return productName;
    }

    public int getQuantity() {
        return quantity;
    }
}

// 套餐类
class Combo {
    private String name;
    private String price;
    private List<ComboItem> items;

    public Combo(String name, String price) {
        this.name = name;
        this.price = price;
        this.items = new ArrayList<>();
    }

    public void addItem(int serialNumber, String productName, int quantity) {
        items.add(new ComboItem(serialNumber, productName, quantity));
    }

    public String getName() {
        return name;
    }

    public String getPrice() {
        return price;
    }

    public List<ComboItem> getItems() {
        return items;
    }
}

// 产品类
class Product {
    private String name;
    private String leftImagePath;
    private String rightImagePath;
    private String model;
    private String screen;
    private String processor;
    private String memory;
    private String camera;
    private String battery;
    private String colors;
    private String price;

    public Product(String name, String leftImagePath, String rightImagePath,
                   String model, String screen, String processor, String memory,
                   String camera, String battery, String colors, String price) {
        this.name = name;
        this.leftImagePath = leftImagePath;
        this.rightImagePath = rightImagePath;
        this.model = model;
        this.screen = screen;
        this.processor = processor;
        this.memory = memory;
        this.camera = camera;
        this.battery = battery;
        this.colors = colors;
        this.price = price;
    }

    // Getters
    public String getName() { return name; }
    public String getLeftImagePath() { return leftImagePath; }
    public String getRightImagePath() { return rightImagePath; }
    public String getModel() { return model; }
    public String getScreen() { return screen; }
    public String getProcessor() { return processor; }
    public String getMemory() { return memory; }
    public String getCamera() { return camera; }
    public String getBattery() { return battery; }
    public String getColors() { return colors; }
    public String getPrice() { return price; }
}

public class ProductPdfGenerator {

    public static void main(String[] args) {
        try {
            // 创建套餐集合
            List<Combo> combos = createComboList();
            
            // 创建产品集合
            List<Product> products = createProductList();

            // 生成PDF（先套餐后产品）
            generateCatalog("C:\\Users\\lenovo\\Desktop\\catalog.pdf", combos, products);

            System.out.println("PDF生成成功！共 " + (combos.size() + products.size()) + " 页");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 创建示例套餐列表
    private static List<Combo> createComboList() {
        List<Combo> combos = new ArrayList<>();

        // 套餐1
        Combo combo1 = new Combo("豪华办公套餐", "¥15,999");
        combo1.addItem(1, "商务笔记本电脑 Ultra", 1);
        combo1.addItem(2, "无线降噪耳机 Elite", 1);
        combo1.addItem(3, "无线鼠标", 1);
        combo1.addItem(4, "机械键盘", 1);
        combos.add(combo1);

        // 套餐2
        Combo combo2 = new Combo("智能生活套餐", "¥8,999");
        combo2.addItem(1, "高端智能手机 Pro Max", 1);
        combo2.addItem(2, "无线降噪耳机 Elite", 1);
        combo2.addItem(3, "智能手表", 1);
        combos.add(combo2);

        // 套餐3
        Combo combo3 = new Combo("全家福套餐", "¥25,999");
        combo3.addItem(1, "商务笔记本电脑 Ultra", 1);
        combo3.addItem(2, "高端智能手机 Pro Max", 2);
        combo3.addItem(3, "无线降噪耳机 Elite", 2);
        combo3.addItem(4, "智能手表", 1);
        combo3.addItem(5, "平板电脑", 1);
        combos.add(combo3);

        return combos;
    }

    // 创建示例产品列表
    private static List<Product> createProductList() {
        List<Product> products = new ArrayList<>();

        products.add(new Product(
                "高端智能手机 Pro Max",
                "C:\\Users\\lenovo\\Pictures\\Screenshots\\1.png",
                "C:\\Users\\lenovo\\Pictures\\Screenshots\\1.png",
                "SP-2024-PRO",
                "6.7英寸 OLED",
                "八核 3.2GHz",
                "12GB RAM + 512GB ROM",
                "后置三摄 108MP+48MP+12MP",
                "5000mAh 支持快充",
                "星空黑/月光银/天际蓝",
                "¥6,999"
        ));

        products.add(new Product(
                "商务笔记本电脑 Ultra",
                "C:\\Users\\lenovo\\Pictures\\Screenshots\\1.png",
                "C:\\Users\\lenovo\\Pictures\\Screenshots\\1.png",
                "NB-2024-ULTRA",
                "15.6英寸 4K",
                "Intel i9 第13代",
                "32GB RAM + 1TB SSD",
                "高清摄像头 1080P",
                "续航16小时",
                "深空灰/玫瑰金",
                "¥12,999"
        ));

        products.add(new Product(
                "无线降噪耳机 Elite",
                "C:\\Users\\lenovo\\Pictures\\Screenshots\\1.png",
                "C:\\Users\\lenovo\\Pictures\\Screenshots\\1.png",
                "HP-2024-ELITE",
                "N/A",
                "主动降噪芯片",
                "蓝牙5.3",
                "N/A",
                "30小时续航",
                "典雅白/科技黑",
                "¥1,999"
        ));

        return products;
    }

    // 生成完整目录PDF（套餐 + 产品）
    public static void generateCatalog(String dest, List<Combo> combos, List<Product> products) throws IOException {
        // 加载字体
        PdfFont font;
        PdfFont boldFont;
        try {
            InputStream fontStream = ProductPdfGenerator.class.getClassLoader()
                    .getResourceAsStream("fonts/锐字云字库宋黑体.ttf");
            if (fontStream == null) {
                throw new IOException("字体文件未找到");
            }

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] data = new byte[1024];
            int bytesRead;
            while ((bytesRead = fontStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }
            buffer.flush();
            byte[] fontBytes = buffer.toByteArray();
            fontStream.close();

            font = PdfFontFactory.createFont(fontBytes, PdfEncodings.IDENTITY_H);
            boldFont = PdfFontFactory.createFont(fontBytes, PdfEncodings.IDENTITY_H);
            System.out.println("成功加载中文字体");
        } catch (Exception e) {
            System.err.println("字体加载失败：" + e.getMessage());
            font = PdfFontFactory.createFont(StandardFonts.HELVETICA);
            boldFont = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
        }

        // 创建PDF
        PdfWriter writer = new PdfWriter(dest);
        PdfDocument pdfDoc = new PdfDocument(writer);
        PageSize pageSize = PageSize.A4.rotate();
        pdfDoc.setDefaultPageSize(pageSize);
        Document document = new Document(pdfDoc);

        int pageNum = 1;

        // 先添加所有套餐页面
        for (Combo combo : combos) {
            pdfDoc.addNewPage();
            PdfCanvas canvas = new PdfCanvas(pdfDoc.getPage(pageNum));
            setBackground(canvas, pageSize, new DeviceRgb(245, 255, 250)); // 浅绿色背景
            addComboContent(document, combo, pageNum, boldFont, font);
            pageNum++;
        }

        // 再添加所有产品页面
        for (Product product : products) {
            pdfDoc.addNewPage();
            PdfCanvas canvas = new PdfCanvas(pdfDoc.getPage(pageNum));
            setBackground(canvas, pageSize, new DeviceRgb(240, 248, 255)); // 浅蓝色背景
            addProductContent(document, product, pageNum, boldFont, font);
            pageNum++;
        }

        document.close();
    }

    // 设置页面背景色
    private static void setBackground(PdfCanvas canvas, PageSize pageSize, DeviceRgb color) {
        canvas.saveState();
        canvas.setFillColor(color);
        canvas.rectangle(0, 0, pageSize.getWidth(), pageSize.getHeight());
        canvas.fill();
        canvas.restoreState();
    }

    // 添加套餐内容
    private static void addComboContent(Document document, Combo combo, 
                                       int pageNum, PdfFont boldFont, PdfFont font) {
        // 左上角：套餐名称
        Paragraph comboName = new Paragraph(pageNum + ". " + combo.getName())
                .setFont(boldFont)
                .setFontSize(32)
                .setFontColor(new DeviceRgb(0, 102, 51))
                .setBold()
                .setFixedPosition(pageNum, 50, 480, 400)
                .setTextAlignment(TextAlignment.LEFT);
        document.add(comboName);

        // 左下角：套餐价格
        Paragraph comboPrice = new Paragraph("套餐价格：" + combo.getPrice())
                .setFont(boldFont)
                .setFontSize(24)
                .setFontColor(new DeviceRgb(204, 0, 0))
                .setBold()
                .setFixedPosition(pageNum, 50, 420, 400);
        document.add(comboPrice);

        // 中间右侧：套餐产品列表
        Paragraph listTitle = new Paragraph("套餐包含产品：")
                .setFont(boldFont)
                .setFontSize(18)
                .setFontColor(new DeviceRgb(51, 51, 51))
                .setFixedPosition(pageNum, 400, 450, 400);
        document.add(listTitle);

        // 创建产品列表表格
        Table itemsTable = new Table(new float[]{80, 300, 100});
        itemsTable.setFixedPosition(pageNum, 400, 150, 380);
        itemsTable.setFont(font);
        itemsTable.setFontSize(14);

        // 表头
        itemsTable.addHeaderCell(new com.itextpdf.layout.element.Cell()
                .add(new Paragraph("序号").setFont(boldFont))
                .setBackgroundColor(new DeviceRgb(230, 230, 230))
                .setBorder(new SolidBorder(new DeviceRgb(200, 200, 200), 1))
                .setTextAlignment(TextAlignment.CENTER));
        
        itemsTable.addHeaderCell(new com.itextpdf.layout.element.Cell()
                .add(new Paragraph("产品名称").setFont(boldFont))
                .setBackgroundColor(new DeviceRgb(230, 230, 230))
                .setBorder(new SolidBorder(new DeviceRgb(200, 200, 200), 1))
                .setTextAlignment(TextAlignment.CENTER));
        
        itemsTable.addHeaderCell(new com.itextpdf.layout.element.Cell()
                .add(new Paragraph("数量").setFont(boldFont))
                .setBackgroundColor(new DeviceRgb(230, 230, 230))
                .setBorder(new SolidBorder(new DeviceRgb(200, 200, 200), 1))
                .setTextAlignment(TextAlignment.CENTER));

        // 添加产品项
        for (ComboItem item : combo.getItems()) {
            itemsTable.addCell(new com.itextpdf.layout.element.Cell()
                    .add(new Paragraph(String.valueOf(item.getSerialNumber())).setFont(font))
                    .setBackgroundColor(new DeviceRgb(255, 255, 255))
                    .setBorder(new SolidBorder(new DeviceRgb(220, 220, 220), 0.5f))
                    .setTextAlignment(TextAlignment.CENTER));
            
            itemsTable.addCell(new com.itextpdf.layout.element.Cell()
                    .add(new Paragraph(item.getProductName()).setFont(font))
                    .setBackgroundColor(new DeviceRgb(255, 255, 255))
                    .setBorder(new SolidBorder(new DeviceRgb(220, 220, 220), 0.5f))
                    .setPaddingLeft(10));
            
            itemsTable.addCell(new com.itextpdf.layout.element.Cell()
                    .add(new Paragraph(item.getQuantity() + " 件").setFont(font))
                    .setBackgroundColor(new DeviceRgb(255, 255, 255))
                    .setBorder(new SolidBorder(new DeviceRgb(220, 220, 220), 0.5f))
                    .setTextAlignment(TextAlignment.CENTER));
        }

        document.add(itemsTable);
    }

    // 添加产品内容（保持原有逻辑）
    private static void addProductContent(Document document, Product product,
                                          int pageNum, PdfFont boldFont, PdfFont font) {
        // 左侧主图片
        try {
            Image leftImage = new Image(ImageDataFactory.create(product.getLeftImagePath()));
            leftImage.setFixedPosition(pageNum, 50, 150);
            leftImage.scaleToFit(300, 400);
            document.add(leftImage);
        } catch (Exception e) {
            System.out.println("警告：产品 " + product.getName() + " 左侧图片加载失败");
            Paragraph placeholder = new Paragraph("[图片位置]")
                    .setFont(font)
                    .setFontSize(14)
                    .setFixedPosition(pageNum, 150, 300, 100);
            document.add(placeholder);
        }

        // 右上角：产品名称
        Paragraph productName = new Paragraph(pageNum + ". " + product.getName())
                .setFont(boldFont)
                .setFontSize(28)
                .setFontColor(new DeviceRgb(0, 51, 102))
                .setBold()
                .setFixedPosition(pageNum, 400, 480, 400)
                .setTextAlignment(TextAlignment.LEFT);
        document.add(productName);

        // 右下角：产品小图片
        try {
            Image rightBottomImage = new Image(ImageDataFactory.create(product.getRightImagePath()));
            rightBottomImage.setFixedPosition(pageNum, 650, 50);
            rightBottomImage.scaleToFit(150, 150);
            document.add(rightBottomImage);
        } catch (Exception e) {
            System.out.println("警告：产品 " + product.getName() + " 右下角图片加载失败");
        }

        // 右侧中下部：产品规格信息
        Table specTable = new Table(2);
        specTable.setFixedPosition(pageNum, 400, 150, 500);
        specTable.setFont(font);
        specTable.setFontSize(12);

        addSpecRow(specTable, "型号：", product.getModel(), boldFont, font);
        addSpecRow(specTable, "屏幕尺寸：", product.getScreen(), boldFont, font);
        addSpecRow(specTable, "处理器：", product.getProcessor(), boldFont, font);
        addSpecRow(specTable, "内存：", product.getMemory(), boldFont, font);
        addSpecRow(specTable, "摄像头：", product.getCamera(), boldFont, font);
        addSpecRow(specTable, "电池：", product.getBattery(), boldFont, font);
        addSpecRow(specTable, "颜色：", product.getColors(), boldFont, font);
        addSpecRow(specTable, "价格：", product.getPrice(), boldFont, font);

        document.add(specTable);
    }

    // 辅助方法：添加规格行
    private static void addSpecRow(Table table, String label, String value,
                                   PdfFont boldFont, PdfFont normalFont) {
        table.addCell(new com.itextpdf.layout.element.Cell()
                .add(new Paragraph(label).setFont(boldFont))
                .setBorder(com.itextpdf.layout.borders.Border.NO_BORDER)
                .setBackgroundColor(new DeviceRgb(255, 255, 255)));

        table.addCell(new com.itextpdf.layout.element.Cell()
                .add(new Paragraph(value).setFont(normalFont))
                .setBorder(com.itextpdf.layout.borders.Border.NO_BORDER)
                .setBackgroundColor(new DeviceRgb(255, 255, 255)));
    }
}